﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using Adex;
using SubSonic.Sugar;
using System.Security;
using MediaMonitor.Common;
using iTextSharp.text;
using iTextSharp.text.html;
using iTextSharp.text.pdf;
using iTextSharp.text.xml;
using iTextSharp.text.html.simpleparser;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Net.Mail;
using System.Net;
using System.Configuration;
using Telerik.Web.UI;

namespace MediaMonitor.Admin
{
    public partial class User_Mgmt_allPdf : Adex.BasePage
    {
        DateTime sDate = DateTime.MinValue, eDate = DateTime.MinValue;
        
        private static string AppName = ConfigurationManager.AppSettings["AppName"].ToString();
        private static string AdminEmail = ConfigurationManager.AppSettings["AdminEmail"].ToString();
        private iTextSharp.text.Font PDF_FONT_DEFAULT;
        private iTextSharp.text.Font PDF_FONT_TH;
        private iTextSharp.text.Font PDF_FONT_BOLD;
        private iTextSharp.text.Font PDF_FONT_GRAY;
        private iTextSharp.text.Font PDF_FONT_LIGHTGRAY;
        private iTextSharp.text.Font PDF_FONT_TITLE;
        private iTextSharp.text.Font PDF_FONT_HEADING;
        private iTextSharp.text.Font PDF_FONT_HEADING_GRAY;
        private iTextSharp.text.Font PDF_FONT_BIG;
        private iTextSharp.text.Font PDF_FONT_BIG_BOLD;
        private iTextSharp.text.Font PDF_FONT_NAV;
        private iTextSharp.text.Font PDF_FONT_GridElements;

        protected void Page_Init(object sender, EventArgs e)
        {
            BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, false);
            string fontpath = Server.MapPath("../");
            BaseFont customfont = BaseFont.CreateFont(fontpath + "Fonts/KOKILA.TTF", BaseFont.CP1252, BaseFont.EMBEDDED);
            Font Kokila = new Font(customfont, 44, Font.BOLD, BaseColor.BLACK);
            PDF_FONT_TITLE = Kokila;
            BaseFont customfontarial = BaseFont.CreateFont(fontpath + "Fonts/ARIAL.TTF", BaseFont.CP1252, BaseFont.EMBEDDED);
            Font ARIAL = new Font(customfontarial, 11, Font.BOLD, BaseColor.BLACK);
            Font ARIAL11 = new Font(customfontarial, 11, Font.BOLD, BaseColor.BLACK);
            Font ARIALNORMAL11 = new Font(customfontarial, 11, Font.NORMAL, BaseColor.BLACK);
            Font ARIALNORMAL7 = new Font(customfontarial, 7, Font.NORMAL, BaseColor.BLACK);
            PDF_FONT_DEFAULT = ARIALNORMAL11;
            PDF_FONT_TH = ARIAL;
            PDF_FONT_BOLD = ARIAL11;
            PDF_FONT_GRAY = new Font(bf, 14, Font.NORMAL, BaseColor.DARK_GRAY);
            PDF_FONT_LIGHTGRAY = new Font(bf, 15, Font.NORMAL, new BaseColor(System.Drawing.Color.FromArgb(141, 141, 141)));
            PDF_FONT_HEADING = new Font(bf, 16, Font.BOLD, BaseColor.WHITE);
            PDF_FONT_HEADING_GRAY = new Font(bf, 18, Font.BOLD, BaseColor.GRAY);
            PDF_FONT_BIG = new Font(bf, 14, Font.NORMAL, BaseColor.BLACK);
            PDF_FONT_BIG_BOLD = new Font(bf, 14, Font.BOLD, BaseColor.BLACK);
            PDF_FONT_NAV = new Font(bf, 14, Font.BOLD, BaseColor.RED);
            PDF_FONT_GridElements = ARIALNORMAL7;
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                Utility.AddDateControlToPage(this.Page);
                SetCalendarDates();
                
            }
        }

        private void SetCalendarDates()
        {

            DataTable dt = NewCommercialLog.Query().DISTINCT().SetSelectList("RFDate").ExecuteDataSet().Tables[0];
            foreach (DataRow dr in dt.Rows)
            {

                RadCalendarDay d1 = new RadCalendarDay(calS);
                d1.Date = Utility.ToDateTime(dr["RFDate"]);
                d1.IsDisabled = false;
                d1.IsSelectable = true;

                d1.ItemStyle.BackColor = System.Drawing.Color.PowderBlue;
                d1.ItemStyle.ForeColor = System.Drawing.Color.White;

                calS.SpecialDays.Add(d1);

                RadCalendarDay d2 = new RadCalendarDay(calE);
                d2.Date = Utility.ToDateTime(dr["RFDate"]);
                d2.IsDisabled = false;
                d2.IsSelectable = true;

                d2.ItemStyle.BackColor = System.Drawing.Color.PowderBlue;
                d2.ItemStyle.ForeColor = System.Drawing.Color.White;
                calE.SpecialDays.Add(d2);
            }
       }
        
        protected void btnSend_Clicked(object sender, EventArgs e)
        {

            bool tmp1 = DateTime.TryParse(calS.SelectedDate.ToShortDateString(), out sDate);
            bool tmp2 = DateTime.TryParse(calE.SelectedDate.ToShortDateString(), out eDate);
           
           
            if (sDate < Utility.ToDateTime("01/01/2000"))
                sDate = Utility.ToDateTime("01/01/2000");

            if (eDate < Utility.ToDateTime("01/01/2000"))
                eDate = Utility.ToDateTime("01/01/2000");
          
            if ((sDate.ToString() != "01/01/2000") && (eDate.ToString() != "01/01/2000"))
            {
                 GetPDF();
            }
            else
            {

                string script = "alert(\"Please select date first!\");";
                ScriptManager.RegisterStartupScript(this, this.GetType(), "ServerControlScript", script, true);

            }

        }
        private void GetPDF()
        {
           
            String Users = String.Empty;
            DataTable dtCompanies = Company.Query().DISTINCT().SetSelectList("CompanyCode").ExecuteDataSet().Tables[0];
            if (dtCompanies.Rows.Count>0) //If Companies Exist in Database
            {
            
            Int32 CompanyCode;
            
            //Loop of Companies
            foreach (DataRow dr in dtCompanies.Rows)
            {
                 CompanyCode = Convert.ToInt32(dr["CompanyCode"].ToString());

                 DataTable dtUsers = VSiteUser.Query().DISTINCT().SetSelectList("Email").WHERE("RoleName", "user").AND("CompanyCode", CompanyCode).ExecuteDataSet().Tables[0];
                 String UserEmails = String.Empty;
                //Loop For Users of Particular Companies
                 foreach (DataRow dr1 in dtUsers.Rows)
                 {
                     UserEmails += dr1["Email"].ToString() +",";

                 }
                 GetPDFDetail(CompanyCode, UserEmails);
                //Send Mail to the Users of Particular Company
            }

             string script = "alert(\"pdf sent successfully!\");";
             ScriptManager.RegisterStartupScript(this, this.GetType(), "ServerControlScript", script, true);

            }

             else
            {
                string script = "alert(\"No Record Exists!\");";
                ScriptManager.RegisterStartupScript(this, this.GetType(), "ServerControlScript", script, true);

            }
        }


        private void GetPDFDetail(Int32 CompanyID, String UserEmails)
        {
            DataSet dsCommercialPDF = new Common.ReportFuncs().GetReportCommercialPdf(Convert.ToInt32(CompanyID), Utility.ToDateTime(sDate as object), Utility.ToDateTime(eDate as object));
            if ((dsCommercialPDF.Tables[0].Rows.Count > 0) || (dsCommercialPDF.Tables[1].Rows.Count > 0) || (dsCommercialPDF.Tables[2].Rows.Count > 0))
            {
                DataTable dtTV = dsCommercialPDF.Tables[0];
                DataTable dtRadio = dsCommercialPDF.Tables[1];
                DataTable dtPress = dsCommercialPDF.Tables[2];

                //  Company company = new Company(hdnCompanyID.Value);
                Company company = new Company(CompanyID); //(not required) Template is change according to Category of Users.
                string pdfImg1 = "firstpage.jpg";
                string pdfImg2 = "secondpage.jpg";
                //By Default for New Commercial , there is only one template for all users
                string homeImageFilePath = Server.MapPath("~") + "\\images\\newcommercialtemplate\\" + pdfImg1;
                string subImageFilePath = Server.MapPath("~") + "\\images\\newcommercialtemplate\\" + pdfImg2;
                // PDF GENERATEION - start

                iTextSharp.text.Image bgHomePage = iTextSharp.text.Image.GetInstance(homeImageFilePath);
                iTextSharp.text.Image bgSubPage = iTextSharp.text.Image.GetInstance(subImageFilePath);
                iTextSharp.text.Rectangle PdfPageSize = new iTextSharp.text.Rectangle(bgHomePage.Width, bgHomePage.Height);
                iTextSharp.text.Document pdfDoc = new iTextSharp.text.Document(PdfPageSize);

                bgHomePage.Alignment = iTextSharp.text.Image.WRITABLE_DIRECT;
                bgSubPage.Alignment = iTextSharp.text.Image.WRITABLE_DIRECT;

                bgHomePage.ScaleToFit(PdfPageSize.Width, PdfPageSize.Height);
                bgSubPage.ScaleToFit(PdfPageSize.Width, PdfPageSize.Height);

                bgHomePage.SetAbsolutePosition(0, 0);
                bgSubPage.SetAbsolutePosition(0, 0);

                MemoryStream memoryStream = new MemoryStream();
                PdfWriter writer = PdfWriter.GetInstance(pdfDoc, memoryStream);

                // Our custom Header and Footer is done using Event Handler
                TwoColumnHeaderFooter PageEventHandler = new TwoColumnHeaderFooter();
                writer.PageEvent = PageEventHandler;

                // Define the page header
                pdfDoc.Open();
                CreatePDFPage_Home(pdfDoc, writer, bgHomePage, "NEW COMMERCIALS");
                CreatePDFPage_Criteria(pdfDoc, writer, bgSubPage, Utility.ToDateTime(sDate), Utility.ToDateTime(eDate));
                CreatePDFPage_TVList(pdfDoc, writer, bgSubPage, dtTV);
                CreatePDFPage_RADIOList(pdfDoc, writer, bgSubPage, dtRadio);
                CreatePDFPage_PRESSList(pdfDoc, writer, bgSubPage, dtPress);
                //Keeps the memoryStream object open when closing the Document (doc)
                writer.CloseStream = false;
                pdfDoc.Close();

                //Moves the pointer to the beginning of the stream. Without this
                //line an empty file is generated and attached to the email.
                memoryStream.Position = 0;

                SendMail(memoryStream, UserEmails); // this is commented to not send Testing mails to client.

              
                // PDF GENERATION - end
            }
           
        }


        private void SendMail(MemoryStream memoryStream,String Users)
        {
            String toAccount = String.Empty;
            String msg = "These are New Commercial";
            String title = AppName + " New Commercial";
            toAccount = Users;
            //toAccount = "agyapals@nascenture.com,sahilk@nascenture.com";
            String MyHost = ConfigurationManager.AppSettings["SMTPHost"].ToString();
            String MySMTPPort = ConfigurationManager.AppSettings["SMTPPort"].ToString();
            String MySMTPSSL = ConfigurationManager.AppSettings["SMTPSSL"].ToString();
            
            String fromAddr = AdminEmail;   //Email Address of Sender
            //String fromAddr="niteshguleria@nascenture.com";
            MailMessage smtpMssg = new MailMessage();
            smtpMssg.From = new MailAddress(fromAddr);

            if (toAccount.Contains(","))
            {
                string[] tos = toAccount.Split(',');
                for (int i = 0; i < tos.Length; i++)
                {
                    if (tos[i] == "," || tos[i] == "")
                    {
                    }
                    else
                    {
                        smtpMssg.To.Add(new MailAddress(tos[i].Replace(",","")));
                    }
                }
            }
            else
            {
                smtpMssg.To.Add(new MailAddress(toAccount));
            }

            smtpMssg.Subject = title;
            smtpMssg.Body = msg;
            smtpMssg.IsBodyHtml = true;
            smtpMssg.Attachments.Add(new Attachment(memoryStream, "NewCommercial.pdf"));

            System.Net.Mail.SmtpClient smtpClient = new System.Net.Mail.SmtpClient(MyHost, Convert.ToInt32(MySMTPPort));
            smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
            if (MySMTPSSL == "true")
            {
                smtpClient.EnableSsl = true;
            }

            try
            {
                smtpClient.Send(smtpMssg);

            }
            catch (Exception ex)
            {

                throw new Exception("Email not sent | Reason: [" + ex.Message + "]");

            }
        }

        private void CreatePDFPage_Home(Document pdfDoc, PdfWriter writer, iTextSharp.text.Image bgImage, string title)
        {
            pdfDoc.NewPage();
            PdfContentByte pcb = writer.DirectContentUnder;
            pcb.AddImage(bgImage);
            Paragraph pTitle = new Paragraph(44.0f, "\n\n\n\n\n" + title, PDF_FONT_TITLE);
            pTitle.Alignment = Rectangle.ALIGN_CENTER;
            Paragraph pDate = new Paragraph(18.0f, "\n\n\n\n\n\n\n\n\n\n\n\n\n" + DateTime.Now.ToString("dd MMMM yyyy"), PDF_FONT_HEADING_GRAY);
            pdfDoc.Add(pTitle);
            pdfDoc.Add(pDate);

        }

        private void CreatePDFPage_Criteria(Document pdfDoc, PdfWriter writer, iTextSharp.text.Image bgImage, DateTime sDate, DateTime eDate)
        {
            pdfDoc.NewPage();
            PdfContentByte pcb1 = writer.DirectContentUnder;
            pcb1.AddImage(bgImage);
            Paragraph pPageHeading = new Paragraph(14.0f, "\n\n\nNEW COMMERCIALS", PDF_FONT_HEADING);
            pPageHeading.Alignment = iTextSharp.text.Element.ALIGN_LEFT;
            pPageHeading.IndentationLeft = 330f;
            pPageHeading.SpacingAfter = 16f;
            pdfDoc.Add(pPageHeading);



            Paragraph pCriteria = new Paragraph();
            pCriteria.Add(new Chunk("\n\n\n\n\n\n\n\n\n\n\n\n\n\n New Commercials", PDF_FONT_BIG_BOLD));
            pCriteria.Alignment = iTextSharp.text.Element.ALIGN_CENTER;
            pdfDoc.Add(pCriteria);

            Paragraph pDate = new Paragraph("From: " + sDate.ToString("dd MMMM, yyyy") + "\n To: " + eDate.ToString("dd MMMM, yyyy"), PDF_FONT_LIGHTGRAY);
            pDate.Alignment = iTextSharp.text.Element.ALIGN_LEFT;
            pDate.IndentationLeft = 330f;

            pdfDoc.Add(pDate);

        }

        private void CreatePDFPage_TVList(Document pdfDoc, PdfWriter writer, iTextSharp.text.Image bgImage, DataTable dtTV)
        {

            if (dtTV.Rows.Count > 0)
            {
                pdfDoc.NewPage();
                PdfContentByte pcb1 = writer.DirectContentUnder;
                pcb1.AddImage(bgImage);
                Paragraph pPageHeading = new Paragraph(14.0f, "\n\n\nTV\n\n\n\n", PDF_FONT_HEADING);
                pPageHeading.Alignment = iTextSharp.text.Element.ALIGN_LEFT;
                pPageHeading.IndentationLeft = 330f;
                pdfDoc.Add(pPageHeading);
                Anchor prodAnchor = new Anchor(".");
                prodAnchor.Name = "TV";
                Paragraph p = new Paragraph();
                p.Add(prodAnchor);
                pdfDoc.Add(p);
                PdfPTable prodTable = GetPDFTable(dtTV);
                pdfDoc.Add(prodTable);

            }

        }


        private void CreatePDFPage_RADIOList(Document pdfDoc, PdfWriter writer, iTextSharp.text.Image bgImage, DataTable dtRadio)
        {

            if (dtRadio.Rows.Count > 0)
            {
                pdfDoc.NewPage();
                PdfContentByte pcb1 = writer.DirectContentUnder;
                pcb1.AddImage(bgImage);
                Paragraph pPageHeading = new Paragraph(14.0f, "\n\n\nRADIO\n\n\n\n", PDF_FONT_HEADING);
                pPageHeading.Alignment = iTextSharp.text.Element.ALIGN_LEFT;
                pPageHeading.IndentationLeft = 330f;
                pdfDoc.Add(pPageHeading);
                Anchor prodAnchor = new Anchor(".");
                prodAnchor.Name = "Radio";
                Paragraph p = new Paragraph();
                p.Add(prodAnchor);
                pdfDoc.Add(p);
                PdfPTable prodTable = GetPDFTable(dtRadio);
                pdfDoc.Add(prodTable);

            }

        }

        private void CreatePDFPage_PRESSList(Document pdfDoc, PdfWriter writer, iTextSharp.text.Image bgImage, DataTable dtPress)
        {

            if (dtPress.Rows.Count > 0)
            {
                pdfDoc.NewPage();
                PdfContentByte pcb1 = writer.DirectContentUnder;
                pcb1.AddImage(bgImage);
                Paragraph pPageHeading = new Paragraph(14.0f, "\n\n\nPRESS\n\n\n\n", PDF_FONT_HEADING);
                pPageHeading.Alignment = iTextSharp.text.Element.ALIGN_LEFT;
                pPageHeading.IndentationLeft = 330f;
                pdfDoc.Add(pPageHeading);
                Anchor prodAnchor = new Anchor(".");
                prodAnchor.Name = "Press";
                Paragraph p = new Paragraph();
                p.Add(prodAnchor);
                pdfDoc.Add(p);
                PdfPTable prodTable = GetPDFTable(dtPress);
                pdfDoc.Add(prodTable);

            }

        }

     
        private PdfPTable GetPDFTable(DataTable dt)
        {
            if (dt.Rows.Count == 0)
                return new PdfPTable(0);

            int columnCount = dt.Columns.Count;
            int rowCount = dt.Rows.Count;
            int tableRows = rowCount + 3;
            iTextSharp.text.pdf.PdfPTable gridTable = new PdfPTable(columnCount);
            gridTable.WidthPercentage = 100;
            var colWidthPercentages = new[] { 7f, 10f, 10f, 20f, 7f, 15f, 20f, 7f,2f };
            gridTable.SetWidths(colWidthPercentages);
            //add headers
            PdfPCell[] arrTh = new PdfPCell[columnCount];
            //Header Bind Start
            for (int i = 1; i < columnCount; i++) 
            {

                string header = "";
                string[] heads = SubSonic.Sugar.Strings.ToWords(dt.Columns[i].ColumnName);
                foreach (string head in heads)
                    header += head + " ";

                
                arrTh[i - 1] = new PdfPCell();
                arrTh[i - 1].AddElement(new Chunk(header, PDF_FONT_BOLD));
                arrTh[i - 1].Border = 0;
                arrTh[i - 1].BorderColorLeft = BaseColor.WHITE;
                arrTh[i - 1].BorderWidthTop = 1f;
                arrTh[i - 1].BorderWidthBottom = 1f;
                if (i == 1)
                {
                    arrTh[i - 1].BorderWidthLeft = 1f;
                    arrTh[i - 1].BorderColorLeft = BaseColor.BLACK;
                    arrTh[i - 1].PaddingLeft = 5f;
                }
                if (i == columnCount - 1)
                {
                    arrTh[i - 1].BorderWidthRight = 1f;
                    arrTh[i - 1].BorderColorRight = BaseColor.BLACK;
                    arrTh[i - 1].Colspan = 2;
                }
                arrTh[i - 1].PaddingTop = 10f;
                arrTh[i - 1].PaddingBottom = 20f;
            }
            //Header Bind End
            arrTh[columnCount - 1] = new PdfPCell();
            gridTable.Rows.Add(new PdfPRow(arrTh));
            int rowIndex = 0;
            
            //Inner Elements Bind Start
            foreach (DataRow dr in dt.Rows)
            {
                PdfPCell[] arrTd = new PdfPCell[columnCount];
                int colIndex = 1;
                for (colIndex = 1; colIndex < columnCount; colIndex++)
                {
                    if (colIndex == columnCount - 1)
                    {

                        arrTd[colIndex - 1] = new PdfPCell();
                        Chunk cImage = new Chunk("PREVIEW", PDF_FONT_GridElements);
                        Chunk cDownload = new Chunk("/Download", PDF_FONT_GridElements);
                        String Url = String.Empty;
                        String FileToDownlod = String.Empty;

                        if (AppUser.GetCountry() == 58)
                        {
                            Url = "http://www.mediamonitor.do/pdf-popup.aspx?id=" + Utility.IsNullStr(dt.Rows[rowIndex][colIndex]);
                            FileToDownlod = "http://www.mediamonitor.do/pdf-popup.aspx?FTD=" + Utility.IsNullStr(dt.Rows[rowIndex][colIndex]);
                        }
                        else
                        {
                            Url = "http://www.mediamonitor.com.tt/pdf-popup.aspx?id=" + Utility.IsNullStr(dt.Rows[rowIndex][colIndex]);
                            FileToDownlod = "http://www.mediamonitor.com.tt/pdf-popup.aspx?FTD=" + Utility.IsNullStr(dt.Rows[rowIndex][colIndex]);
                        }
                          //  Url = "http://localhost:5919/MediaMonitor/pdf-popup.aspx?id=" + Utility.IsNullStr(dt.Rows[rowIndex][colIndex]);
                            //FileToDownlod = "http://localhost:5919/MediaMonitor/pdf-popup.aspx?FTD=" + Utility.IsNullStr(dt.Rows[rowIndex][colIndex]);
                        cImage.SetAction(PdfAction.JavaScript("app.launchURL(\'" + Url + "\',true);", null));
                        cDownload.SetAction(PdfAction.JavaScript("app.launchURL(\'" + FileToDownlod + "\',true);", null));
                        arrTd[colIndex - 1].AddElement(cImage);
                        arrTd[colIndex - 1].AddElement(cDownload);
                        arrTd[colIndex - 1].Border = 0;
                        //String Fullurl = Server.MapPath("~") + "\\NewCommercials\\" + Utility.IsNullStr(dt.Rows[rowIndex][colIndex], "");
                       
                        //cImage.SetAction(PdfAction.JavaScript("app.launchURL(\'www.google.com\',true);", null)); 
                        //cImage.SetAction(PdfAction.JavaScript("app.launchURL(\'www.google.com\',true);", null)); 
                       // cImage.SetAction(PdfAction.JavaScript("app.alert('JS says')",null));
                        //cImage.SetAction(PdfAction.JavaScript("app.window.open('"  + Fullurl + "','_blank')", null));
                        //String StrDet= "<script type='text/javascript'>window.open('" + Fullurl + "','_blank');</script>";
                        //detail.Reference = Fullurl;
                       
                       
                        //cImage.SetAction(PdfAction.JavaScript("app.media.openPlayer({ alerter: null });", null));
                        
                        //Anchor detail = new Anchor(cImage);
                        //detail.Reference = "http://localhost:5919/MediaMonitor/admin/pdf-popup.aspx?id=" + Utility.IsNullStr(dt.Rows[rowIndex][colIndex]);
                        //Paragraph p1 = new Paragraph();
                        //p1.Alignment = Rectangle.ALIGN_TOP;
                        //p1.Add(detail);
                       
                      }
                    else
                    {
                        arrTd[colIndex - 1] = new PdfPCell();
                        arrTd[colIndex - 1].AddElement(new Chunk(Utility.IsNullStr(dt.Rows[rowIndex][colIndex], ""), PDF_FONT_GridElements));
                        arrTd[colIndex - 1].Border = 0;
                    }
                }

                arrTd[colIndex - 1] = new PdfPCell();
                
                arrTd[colIndex - 1].Border = 0;
                arrTd[colIndex - 1].PaddingTop = 10f;
              
                gridTable.Rows.Add(new PdfPRow(arrTd));
                rowIndex++;
            }
             //Inner Elements Bind End

            return gridTable;
        }
      
    }
}